jQuery.noConflict();
//var host=document.location.host;
//alert(host);
var num = 0;
/**
 * 加载数据
 */
function getSource(start,limit,fsiteid){
	start = start == undefined ? 0 : start;
	var data = {"start": start,"limit":limit};
	jQuery.ajax({
		url:"list?fsiteid="+fsiteid,
		data:data,
		type:"get",
		dataType:"json",
		cache:false,
		success:function(data){
			//bindGridList(data);
		//alert($('choose_node').value);
		if($('choose_node').value=="")
		{
		        josnTreeList(data);
		}
		else
		{
			josnTreeList(data,$('choose_node').value);
		}
		        //tree.terminate();
			//pager(data.total,data.limit,start);
			//if(!limit)
				//page(data.total,data.limit,1,"pager","getSource",true);
		},
		error:function(data){
			
			$.growlUI('数据加载出错'); 
		}
	   
	});
}
//添加栏目再加载
function regetSource(select_id){
	/*
	var start = 0; 
	var limit = 1000;
	var sort = $('sort').value;
	var fcolumnlevel = $('fcolumnlevel').value;
	var fcolumngp = $('fcolumngp').value;
	var fsiteid = $('fsiteid').value;
	var ID = $('ID').value;
	var fcolumnname = $('fcolumnname').value;
	var fcolumnurl = $('fcolumnurl').value;
	var IndexTemplate = $('IndexTemplate').value;
	var fchecked = $('fchecked').value;
	var choose_node = $('choose_node').value;
	*/
		document.form1.action = "addcolumn";
		document.form1.submit();
	/*
	var data = {"start": start,"limit":limit,"sort":sort,"fcolumnlevel":fcolumnlevel,"fcolumngp":fcolumngp,"fsiteid":fsiteid,"fcolumnname":fcolumnname,"fcolumnurl":fcolumnurl,"IndexTemplate":IndexTemplate,"fchecked":fchecked,"choose_node":select_id};
	jQuery.ajax({
		url:"addcolumn",
		data:data,
		type:"post",
		dataType:"json",
		cache:false,
		success:function(data){
			//josnTreeList(data,select_id);
		//$('choose_node').value = select_id;
		//document.form1.action = "refreshcolumn";
		//document.form1.submit();
		},
		error:function(data){
			
			jQuery.growlUI('数据加载出错'); 
		}
	   
	});*/
}
//发布/取消发布栏目再加载
function publish(check,fsiteid,ID){
	var checkvalue = check;
	//alert(checkvalue);
	var start = 0; 
	var limit = 1000;
	var data = {"start": start,"limit":limit,"ID": ID,"fsiteid":fsiteid,"checkvalue":checkvalue};
	jQuery.ajax({
		url:"publishcolumn",
		data:data,
		type:"post",
		dataType:"json",
		cache:false,
		success:function(data){
			josnTreeList(data,ID,"");
			if(checkvalue==1)
			{
				jQuery.growlUI('发布成功');
			}
			else
			{
				jQuery.growlUI('已取消发布');
			}
		},
		error:function(data){
			
			jQuery.growlUI('数据加载出错'); 
		}
	   
	});
}
//清空栏目
function clear(ID){
	var data = {"ID": ID};
	jQuery.ajax({
		url:"clearcolumn",
		data:data,
		type:"post",
		dataType:"json",
		cache:false,
		success:function(data){
			if(data.res==0)
			{
				alert("没有找到与该栏目关联的文章");
			}
			else if(data.res>0)
			{
				alert("所有文章关联清空完成");
			}
		},
		error:function(data){
			
			jQuery.growlUI('数据加载出错'); 
		}
	   
	});
}
//删除栏目
function delete_column(Array_ID){
	//alert(Array_ID.length);
	var ID_STRING="";
	for(var DList=0;DList<Array_ID.length;DList++)
	{
		ID_STRING = ID_STRING + Array_ID[DList] + ",";
	}
	//ID_STRING=ID_STRING.toString().substring(0,ID_STRING.length-1);
	//alert(ID_STRING);
	//document.form1.action = "deletecolumn";
	//document.form1.submit();
	
	var data = {"ID": ID_STRING};
	jQuery.ajax({
		url:"deletecolumn",
		data:data,
		type:"post",
		dataType:"json",
		cache:false,
		success:function(data){
		    //jQuery.growlUI('删除成功');
		//alert(data.source[0].fsiteid);
		    //jQuery.growlUI('删除成功');
		    document.form1.action = "refreshcolumn";
			document.form1.submit();
		},
		error:function(data){
			//document.form1.action = "refreshcolumn";
			//document.form1.submit();
			jQuery.growlUI('删除失败'); 
		}
	   
	});
	
}
//获取传入栏目的子栏目最高排序号
function getCount(start,limit,fsiteid,id,nowsort,level){
	start = start == undefined ? 0 : start;
	var data = {"start": start,"limit":limit};
	if(fsiteid==""){ return;}
	jQuery.ajax({
		url:"columnCount?fsiteid="+fsiteid+"&&id="+id,
		data:data,
		type:"get",
		dataType:"json",
		cache:false,
		success:function(data){
		
		if(level==1)
		{
			//找到子栏目
			if(data.source.length!=1)
			{
				//alert("gg");
				//alert(data.source[0].fsortnum*1);
			    var rate = "0.";
			    for(i=0;i<level;i++)
			    {
			    	rate = rate+"00";
			    }
			    rate += 1;
				$('sort').value = (data.source[0].fsortnum*1+rate*1).toFixed((level*1)*3);
			}
			//没有找到
			else
			{
				//alert("f");
				var rate = "0.";
			    for(i=0;i<level;i++)
			    {
			    	rate = rate+"00";
			    }
			    rate += 1;
				$('sort').value = (nowsort*1+rate*1).toFixed((level*1)*3);
			}
		}
		else
		{
			//找到子栏目
			if(data.source.length!=0)
			{
				
				var rate = "0.";
			    for(i=0;i<level;i++)
			    {
			    	rate = rate+"00";
			    }
			    rate += 1;
				$('sort').value = (data.source[0].fsortnum*1+rate*1).toFixed((level*1)*3);
			}
			//没有找到
			else
			{
				var rate = "0.";
			    for(i=0;i<level;i++)
			    {
			    	rate = rate+"00";
			    }
			    rate += 1;
				$('sort').value = (nowsort*1+rate*1).toFixed((level*1)*3);
			}
			//alert($('sort').value);
		}
		regetSource(id);
		},
		error:function(data){
			getCount(start,limit,fsiteid,id,nowsort,level);
			//jQuery.growlUI('数据加载出错!!!!'); 
		}
	   
	});
}
function josnTreeList(data){
	//清空一次tree层
	var selected_id;var pub=false;
	selected_id = arguments.length>=2? arguments[1]:null;
	if(arguments.length==3){ pub = true;};
	$('tree_container').innerHTML = "";
	num++;
	if(num>1)
	{
		document.form1.action = "refreshcolumn";
		document.form1.submit();
	}
	//重新生成tree
	tree = new Mif.Tree({
		container: $('tree_container'),
		forest: false,
		initialize: function(){
		    //this.initCheckbox('deps');
			new Mif.Tree.KeyNav(this);
			/*拖动
			new Mif.Tree.Drag(this, {
				onDrag: function(){
					//inject book inside book not allowed;
					if(this.target && this.target.type=='book' && this.current.type=='book' && this.where=='inside'){
						this.where='notAllowed';
					}
					//$('destination').innerHTML=this.target ? this.target.name : '';
					//$('where').innerHTML=this.where;
				},
				onStart: function(){
					//$('source').innerHTML=this.current.name;
				},
				onComplete: function(){
					//$('destination').innerHTML='';
					//$('where').innerHTML='';
					//$('source').innerHTML='';
				}
			});
			*/
		},
		types: {
			folder:{
				openIcon: 'mif-tree-open-icon',
				closeIcon: 'mif-tree-close-icon'
			},
			loader:{
				openIcon: 'mif-tree-loader-open-icon',
				closeIcon: 'mif-tree-loader-close-icon',
				dropDenied: ['inside','after']
			},
			disabled:{
				openIcon: '',
				closeIcon: '',
				dragDisabled: true,
				cls: 'disabled'
			},
			book:{
				openIcon: 'mif-tree-book-icon',
				closeIcon: 'mif-tree-book-icon',
				loadable: true
			},
			bin:{
				openIcon: 'mif-tree-bin-open-icon',
				closeIcon: 'mif-tree-bin-close-icon'
			}
		},
		dfltType:'folder',
		height: 18,
		onCopy: function(from, to, where, copy){
			if(from.getParent()==copy.getParent()){
				copy.set({
					property: {
						name: 'copy '+from.name
					}
				});
			}
		},
		onRename: function(node, newName, oldName){
		    //成功重命名后
		}
	})
	var json ="";
	if(data.source.length==0)
	{
		 json='[{"property": {"name": "'+data.Wname.ftitle+'","hasCheckbox": false},"type": "book","children":[{"property": {"name": "no column exist"},"type":"disabled"},';
	}
	else
	{
		json='[{"property": {"name": "'+data.Wname.ftitle+'","hasCheckbox": false},"type": "book","children":[';
	}
	var currentlevel = 1;
	var Index = 0;
	jQuery.each(data.source,function(i,columnTree){
		Index++;//alert(columnTree.fcolumnlevel);
		//alert(columnTree.fcolumnname);
		if(columnTree.fcolumnlevel == currentlevel)
		{
		json +='{"property":{"name":"'+columnTree.fcolumnname+'","id":"'+columnTree.id+'","ftemplate":"'+columnTree.ftemplateguid+'","fcolumnlevel":"'+columnTree.fcolumnlevel+'","fcolumngp":"'+columnTree.fcolumngp+'","fcolumnurl":"'+columnTree.fcolumnurl+'","fsortnum":"'+columnTree.fsortnum+'","fchecked":"'+columnTree.fchecked+'"}},';
		}
		else if(columnTree.fcolumnlevel > currentlevel)
		{
			currentlevel++;
			json = json.substring(0,json.length-2);
			json +=',"children":[{"property": {"name": "'+columnTree.fcolumnname+'","id":"'+columnTree.id+'","ftemplate":"'+columnTree.ftemplateguid+'","fcolumnlevel":"'+columnTree.fcolumnlevel+'","fcolumngp":"'+columnTree.fcolumngp+'","fcolumnurl":"'+columnTree.fcolumnurl+'","fsortnum":"'+columnTree.fsortnum+'","fchecked":"'+columnTree.fchecked+'"}},';
		}
		else if(columnTree.fcolumnlevel < currentlevel)
		{
			while(columnTree.fcolumnlevel!=currentlevel)
			{
				currentlevel--;
				json = json.substring(0,json.length-1);
				json +=']},';
			}
			json +='{"property":{"name":"'+columnTree.fcolumnname+'","id":"'+columnTree.id+'","ftemplate":"'+columnTree.ftemplateguid+'","fcolumnlevel":"'+columnTree.fcolumnlevel+'","fcolumngp":"'+columnTree.fcolumngp+'","fcolumnurl":"'+columnTree.fcolumnurl+'","fsortnum":"'+columnTree.fsortnum+'","fchecked":"'+columnTree.fchecked+'"}},';
		}
		//alert(json);
	})
	json = json.substring(0,json.length-1);
	json +=']';
	for(i=currentlevel;i>=1;i--)
	{
		json +='}]';
	}
	//alert(json);
		//tree.initSortable();
	//var json =[{"property": {"name": "21","hasCheckbox": false},"type": "book","children":[]}];
	//alert(json);
	json = eval(json);
	tree.load({
		
		//url: '../../js/mootools/forest.json'
		json : json
		
	})
    .addEvent('select',function(node){
    	var node = tree.selected;
    	if(node.name!=data.Wname.ftitle){$('id_show').innerHTML= node.id;$('ID').value=node.id;}else{$('id_show').innerHTML= "";$('ID').value="";}
    	if(node.name!=data.Wname.ftitle){$('fcolumnname').value= node.name;}else{$('fcolumnname').value= "";}
    	if(node.name!=data.Wname.ftitle){$('fcolumnurl').value= node.fcolumnurl;}else{$('fcolumnurl').value= "";}
    	if(node.name!=data.Wname.ftitle){$('IndexTemplate').value= node.ftemplate;}else{$('IndexTemplate').value= "";}
    	if(node.name=="no column exist")
		{
		    tree.select(tree.root);$('fcolumnname').value= "";
		}
    	if(node.name!=data.Wname.ftitle)
    	{
    		$('fcolumnlevel').value= node.fcolumnlevel;
    		var ColName = "";
    		switch(node.fcolumnlevel)
    		{
    		  case "1": ColName = "一级";break;
    		  case "2": ColName = "二级";break;
    		  case "3": ColName = "三级";break;
    		  case "4": ColName = "四级";break;
    		  case "5": ColName = "五级";break;
    		  case "6": ColName = "六级";break;
    		  case "7": ColName = "七级";break;
    		  case "8": ColName = "八级";break;
    		  case "9": ColName = "九级";break;
    		  case "10":ColName = "十级";break;
    		}
    		$('level_show').innerHTML = ColName;
    	}
    	else
    	{
    		$('fcolumnlevel').value= "";
    		
    		$('level_show').innerHTML = "";
    	}
    	if(node.name!=data.Wname.ftitle){$('fcolumngp').value= node.fcolumngp;}else{$('fcolumngp').value= "";}
    	if(node.name!=data.Wname.ftitle){$('sort').value= node.fsortnum;}else{$('sort').value= "";}
    	if(node.name!=data.Wname.ftitle){$('fchecked').value= node.fchecked;}else{$('fchecked').value= "";}
    	
    	if($('id_show').innerHTML=="undefined")$('id_show').innerHTML="";
    	if($('fcolumnname').value=="undefined")$('fcolumnname').value="";
    	if($('fcolumnurl').value=="undefined")$('fcolumnurl').value="";
    	if($('IndexTemplate').value=="undefined")$('IndexTemplate').value="";
    	if($('fcolumngp').value=="undefined")$('fcolumngp').value="";
    	if($('fchecked').value=="0"){$('check_show').innerHTML="未发布";}
    	else if($('fchecked').value=="1"){$('check_show').innerHTML="已发布";}
    	else{$('check_show').innerHTML="";}
	});
	//alert(num);
	var root = data.Wname.ftitle;
		tree.root.recursive(function(){
			
			this.toggle();
		})
		 //tree.select(tree.root);
		//alert(selected_id);
			//var node = tree.root.getFirst().getNextVisible().getNextVisible().getNextVisible().getNextVisible().id;
		//alert(selected_id);
		//selected_id = selected_id.replace("S","");
		//alert((""+selected_id).indexOf("S"));
		//if((""+selected_id).indexOf("S")!=-1){selected_id = parseInt((""+selected_id).replace("S",""));} 
		if(tree.root.getFirst().name=="no column exist")
		{
		    tree.select(tree.root);
		    
		}
		else
		{
			
			if(selected_id==null||selected_id=="undefined")
			{ 
					tree.select(tree.root);
			}
			else if(selected_id=="last")
			{ 
					tree.select(tree.root.getLast());
			}
			else
			{
				
				var jj=true;
				var node = tree.root;
				if((""+selected_id).indexOf("S")!=-1)
				{
					selected_id = parseInt((""+selected_id).replace("S",""));
					while(jj)
					{
						if(node.getNextVisible()!=false)
						{
							node = node.getNextVisible();
							if(node.id==selected_id)
							{
								
							    	tree.select(node);
							    	jj=false;
							    
							}
						}
						
					}
				}
				else
				{
					while(jj)
					{
						if(node.getNextVisible()!=false)
						{
							node = node.getNextVisible();
							if(node.id==selected_id)
							{
								//alert(node.id);
							    if(pub==false)
							    {
							    	if(node.getLast()==null){tree.select(node);}
							    	else{tree.select(node.getLast());}
							    	jj=false;
							    }
							    else
							    {
							    	tree.select(node);
							    	jj=false;
							    }
							}
						}
						
					}
				}
			}
		}
	var	first_id = tree.root.getFirst().id;
	var last_id = tree.root.getLast().id;
		//alert(node);
		
	/*
	$('rename').addEvent('click', function(){
		var node=tree.selected;
	    if(!node) return;
	    if($('fcolumnname').value=="")
	    {alert("栏目名称不可以为空"); $('fcolumnname').focus();return;}
	    node.rename();
	});
	*/
	$('tree_container').focus();
	$('tree_container').onkeypress=trace;
	function trace(){

		var val= event.keyCode;
        //alert(val);

		switch(val){
			case 119:
				$('MovePrevious').click();
			break;
			case 115:
				$('MoveNext').click();
				break;
			case 116:
				if(!tree.selected.isOpen())
				{
					tree.selected.toggle();
				}
				else
				{
					//tree.selected.goLeft();
					//tree.selected.toggle();
				}
				break;
			case 13:
				if($('fsiteid').value==""||$('fsiteid').value=="--请选择站点--")
				{
					
				}
				else
				{
					$('add_node').click();
				}
			break;
			case 100:
				$('BtnDel').click();
			break;
			case 114:
				//window.location.reload();
				document.form1.action = "refreshcolumn";
				document.form1.submit();
			break;


		}

	}
	$('BtnSave').addEvent('click', function(){
		if(tree.selected==tree.root)
		{
			return false;
		}
		
				$('choose_node').value = "S"+tree.selected.id;

		document.form1.action = "savecolumn";
		document.form1.submit();
	});
	$('BtnDel').addEvent('click', function(){
		
		if(tree.selected==tree.root){{jQuery.growlUI("请选择要删除的栏目");return;}}
		var node=tree.selected;
		if(!node.isOpen()) node.toggle();
		if($('fsiteid').value==""||$('fsiteid').value=="--请选择站点--"){return;}
		/*
		if(confirm('确定要将栏目<'+node.name+'>及其关联的子栏目删除吗？')){
			document.form1.action = "deletecolumn";
			document.form1.submit();
		}else{*/
		if(confirm('确定要将栏目<'+node.name+'>及其关联的子栏目删除吗？')){
			var index_d = 0;
			var select_fcolumnlevel = node.fcolumnlevel;
			var select_id = node.id;
			var id_list = [select_id];
			var ii=true;
	        
			var start_fcolumnlevel = node.fcolumnlevel;
			var start_node = node;
			var kk=true;
			
			while(kk)
			{
				
				    if(node.getNextVisible()==false)
				    {kk=false;}
				    else
				    {
				    	node = node.getNextVisible();
				    	
				    	if(start_fcolumnlevel<node.fcolumnlevel)
				    	{
							id_list.push(node.id);
							//调试用
							/*
							tree.select(node);
							alert(node.id);
							*/
				    	}
				    	else
				    	{
				    		kk = false;
				    	}
				    	
				    	
				    }
			}
			//alert(start_node.id);
			if(start_node.getPreviousVisible())
		    {
					$('choose_node').value = start_node.getPreviousVisible().id;
			}
			else
			{
					$('choose_node').value = "";
			}
			//tree.select(start_node.getPreviousVisible());
			//alert($('choose_node').value);
			delete_column(id_list);
			
			
		}else{}
	}
	/*}*/);
	tree.options.beforeRename=function(node, oldName, newName){
		if(confirm('确认将栏目<'+oldName+'>重新命名为<'+newName+'>?')){
			this.renameComplete();
		}else{
			this.renameCancel();
		}
	};
	/*
	$('BtnPublish').addEvent('click', function(){
		
		if($('fcolumnname').value==""){{jQuery.growlUI("请选择要发布的栏目");return;}}
		var current=tree.selected;
		publish("1",$('fsiteid').value,current.id);
		
		
	});
	
	$('BtnCancel').addEvent('click', function(){
		
		if($('fcolumnname').value==""){{jQuery.growlUI("请选择要取消发布的栏目"); return;}}
		var current=tree.selected;
		publish("0",$('fsiteid').value,current.id);
		
		
	});	
	*/
    $('BtnClean').addEvent('click', function(){
		
		if($('fcolumnname').value==""){{jQuery.growlUI("请选择要清空文章关联的栏目"); return;}}
		var current=tree.selected;
		clear(current.id);
		
		
	});	
	
    $('MoveNext').addEvent('click', function(){
    	var current = tree.selected;
    	if(current.getNextVisible()!=false)
    	{
    		tree.select(current.getNextVisible());
    	}
    	else tree.select(tree.root);
    	    
	});
    $('MovePrevious').addEvent('click', function(){
    	var current = tree.selected;
    	if(current.getPreviousVisible()!=false)
    	{
    		tree.select(current.getPreviousVisible());
    	}
    	else
    	{
    		var lastNode=tree.root.getLast();
    		while(lastNode.getNextVisible()!=false)
    		{
    		   lastNode = lastNode.getNextVisible();	
    		}
    		tree.select(lastNode);
    	}
    	    
	});	
	$('add_node').addEvent('click', function(){
		//alert($('where').options[$('where').selectedIndex].text);
		var current=tree.selected;//alert(current.fsortnum);
		if(current.fcolumnlevel==7)
		{
			jQuery.growlUI("达到栏目层级上限");return;
		}
		if(!current){ jQuery.growlUI("请选择一条栏目"); return;}
		if($('fcolumnname').value==""&&!current){jQuery.growlUI("栏目名不能为空");return;}
		if(!current.isOpen()) current.toggle();
		if($('fsiteid').value==""||$('fsiteid').value=="--请选择站点--"){return;}
		if($('ID').value==""&&current){
			Index++;
			
			if($('fcolumnname').value=="")
			{
				if(tree.root.getLast().name == "no column exist")
				{
					tree.add({
						property: {name: '新建栏目',fcolumnlevel:1,fsortnum:Index,fcolumngp:9999}
				
					}, current, 'inside');
				}
				else
				{
					var Newsort = parseInt(tree.root.getLast().fsortnum)+1;
					tree.add({
						property: {name: '新建栏目',fcolumnlevel:1,fsortnum:Newsort,fcolumngp:9999}
				
					}, current, 'inside');
				}
			}else {
				
				if(tree.root.getLast().name == "no column exist")
				{
					
				tree.add({
					property: {name: $('fcolumnname').value,fcolumnlevel:1,fsortnum:Index,fcolumngp:9999}
			//chrome//}, current, $('where').getElement(':selected').innerHTML);
				}, current, 'inside');
				}
				else
				{
					var New_sort = parseInt(tree.root.getLast().fsortnum)+1;
					tree.add({
						property: {name: $('fcolumnname').value,fcolumnlevel:1,fsortnum:New_sort,fcolumngp:9999}
					}, current, 'inside');
				}
				
			}
			jQuery('fcolumnlevel').value=1;
			jQuery('fcolumngp').value=9999;
			jQuery('sort').value=Index;
			/*
			
			alert(sort);
			*///this.tree.$getIndex()
			$('choose_node').value = "last";
			
				regetSource(current.id);
			
			
			//delete tree;
		}
		else
		{
			Index++;
			/*
		tree.add({
			property: {name: $('fcolumnname').value}
	//chrome//}, current, $('where').getElement(':selected').innerHTML);
		}, current, 'inside');*/
		$('fcolumnlevel').value=parseInt(current.fcolumnlevel)+1;
		$('fcolumngp').value=current.id;	
		//alert(this.indexOf(current));
		$('choose_node').value = current.id;
		getCount(0,1000,$('fsiteid').value,current.id,current.fsortnum,current.fcolumnlevel);
		}
		//delete tree;
		return false;
	});
}
